import os
import re
import sys
import urllib
import urllib2
import socket
import json
import xbmc
import xbmcaddon
import xbmcgui

ADDON_ID = 'smartdns'
Addon = xbmcaddon.Addon(id=ADDON_ID)
ADDON_TITLE = Addon.getAddonInfo('name')
ADDON_ICON = Addon.getAddonInfo('icon')

DEBUG = False

class SmartDNS(object):

    STR_ADDON_TITLE = 30000
    STR_SUCCESS_TEXT = 30001
    STR_FAILED_TEXT = 30002
    STR_NETERR_TEXT = 30003
    STR_TIMEOUT_TEXT = 30004
    STR_SMARTDNS_URL = 'https://www.overplay.net/api/user/ddwrt/update_smartdns.php?user=%s&pass=%s'
    FUN_NOTIFICATION = 'XBMC.Notification(%s, %s, %d, %s)'
    NOFITY_TIME = 5000

    def __init__(self):
        self.__log('started')
        self.get_settings()
        self.do_update()
        self.__log('done')

    def do_update(self):
        try:
            full_url = self.STR_SMARTDNS_URL % (self.user_id, self.password)
            req = urllib2.Request(url=full_url)
            f = urllib2.urlopen(req)
            json_string = f.read() 
            self.__log(json_string)
            
            parsed_json = json.loads(json_string)
            if 'success' in parsed_json:
                error = parsed_json['msg']
                message =  Addon.getLocalizedString(self.STR_FAILED_TEXT) % (error)
            else:
                ip = parsed_json['ip']
                updated = parsed_json['updated']
                dns_server = parsed_json['dns_server']
                message =  Addon.getLocalizedString(self.STR_SUCCESS_TEXT) % (ip)
                
        except urllib2.URLError, e:
            if isinstance(e.reason, socket.timeout):
                message =  Addon.getLocalizedString(self.STR_TIMEOUT_TEXT)
            else:
                self.__log(e.reason)
                message =  Addon.getLocalizedString(self.STR_NETERR_TEXT)

        except socket.timeout:
            message =  Addon.getLocalizedString(self.STR_TIMEOUT_TEXT)
            
        self.__log(message)
        notification = self.FUN_NOTIFICATION % (ADDON_TITLE, message, self.NOFITY_TIME, ADDON_ICON)
        xbmc.executebuiltin(notification)

    def get_settings(self):
        self.user_id = Addon.getSetting('user_id')
        self.__log('settings: user_id=%s' % self.user_id)
        self.password = Addon.getSetting('password')
        self.__log('settings: len(password)=%d' % len(self.password))
        
    def __log(self, msg):
        xbmc.log('%s: %s' % (ADDON_TITLE, msg))

if __name__ == '__main__':
    Uploader = SmartDNS()
